var fs = require('fs');
var readline = require('readline');

var files = fs.readdirSync('data/result/');
var data = [];
var fileNum = 0;

function getDir(url) {
  var arr = url.split('.');
  var len = arr.length;
  return arr[len - 1];
}

function readFiles(i) {
  if (files[i][0] === '.') {
    i++;
    return readFiles(i)
  }
  var nameKey = getDir(files[i]);
  var lines = [];
  var ds = readline.createInterface({
    input: fs.createReadStream('data/result/' + files[i])
  });
  ds.on('line', function (line) {
    lines.push({name: nameKey, value: JSON.parse(line)})
  });
  var senderTimer;
  ds.on('close', function () {
    console.log('start');
    data.push(lines);
    if (i < files.length - 1) {
      i++;
      readFiles(i)
    }
  })
}

module.exports = function (io) {
  readFiles(fileNum);



  // io.on('connection', function (socket) {
    var senderTimer;
    var lineNum = 0;

    function sendPkg() {
      senderTimer = setTimeout(function () {
        for (var t = 0; t < data.length; t++) {
          if (lineNum < data[t].length) {
            // console.log('send  '+data[t][lineNum].name +lineNum);
            // socket.emit(data[t][lineNum].name, data[t][lineNum].value);
            io.getClient().publish('/channel/'+data[t][lineNum].name,data[t][lineNum].value )
          }
        }
        lineNum++;
        sendPkg()
      }, 1000)
    }

    sendPkg();
    // socket.on('disconnect', function () {
    //   if (senderTimer) {
    //     clearTimeout(senderTimer)
    //   }
    // })
  // })
};